import axios from "axios";
import Qs from "qs";
import { Message } from "element-ui";
import router from "@/router";

let baseUrl = "/control";

if (process.env.NODE_ENV === "production") {
  baseUrl = "/control";
}

function unauthorized() {
  router.push({
    path: "/login",
  });
}

const rejectErrors = [
  (data) => {
    console.log(data);

    Message.closeAll();
    Message({
      message: data.errMsg || "操作失败。",
      type: "error",
      duration: 5000,
    });

    if (data.errorCode === "401") {
      unauthorized();
    }
    if (data.code === "401") {
      unauthorized();
    }
  },
];

function request() {
  const api = axios.create({
    baseURL: baseUrl,
    timeout: 60000, // 请求时间超过60秒视为超时
    withCredentials: true,
    headers: {
      "X-Requested-With": "XMLHttpRequest",
    },
    paramsSerializer: function (params) {
      return Qs.stringify(params, { arrayFormat: "repeat", allowDots: true });
    },
  });
  api.interceptors.request.use(
    (config) => {
      return config;
    },
    (error) => {
      if (
        error.response &&
        error.response.status &&
        error.response.status === 401
      ) {
        unauthorized();
      }
      rejectErrors.forEach((f) => f(error.response.data));
      return Promise.reject(error);
    }
  );
  api.interceptors.response.use(
    (response) => {
      const data = response.data;

      if (response.config.showMessage) {
        Message({
          message: data.errMsg || "操作成功",
          type: "success",
          duration: 1000,
        });
      }

      if (!data || data.errCode !== 0) {
        rejectErrors.forEach((f) => f(data));
        return Promise.reject(data.msg);
      }

      return data;
    },
    (error) => {
      if (
        error.response &&
        error.response.status &&
        error.response.status === 401
      ) {
        unauthorized();
      }
      rejectErrors.forEach((f) => f(error.response.data));
      return Promise.reject(error);
    }
  );

  return api;
}

const requestInstance = request();

export { baseUrl, rejectErrors, unauthorized };
export default requestInstance;
